package store.lunangangster.nodeflow.rt.element.flow;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import store.lunangangster.nodeflow.enums.FlowType;
import store.lunangangster.nodeflow.exception.ExecuteException;
import store.lunangangster.nodeflow.rt.DataBus;
import store.lunangangster.nodeflow.rt.element.Executable;
import store.lunangangster.nodeflow.rt.element.Identifiable;
import store.lunangangster.nodeflow.rt.element.Node;

public class SwitchFlow extends Flow {

  private Node switchNode;

  @Override
  public void execute(Integer slotIndex) {
    try {
      switchNode.execute(slotIndex);
      String switchResultKey = switchNode.getNodeComponent().getSwitchResultKey();
      String switchNodeId = (String) DataBus.getSlot(slotIndex).getData(switchResultKey);
      if (StrUtil.isBlank(switchNodeId)) {
        throw new ExecuteException("SwitchFlow execute fail: switchResult is blank");
      }
      Executable selectedNode = null;
      if (!CollUtil.isEmpty(this.executableList)) {
        for (Executable executable : this.executableList) {
          // no check
          Identifiable nodeOrChain = (Identifiable) executable;
          if (nodeOrChain.getId().equals(switchNodeId)) {
            selectedNode = executable;
            break;
          }
        }
      }
      if (selectedNode == null) {
        throw new ExecuteException(String.format("SwitchFlow execute fail: not found nodeId[%s] in SwitchList", switchNodeId));
      }
      // 执行被选中的节点
      selectedNode.execute(slotIndex);
    } finally {
      switchNode.getNodeComponent().removeSwitchResultKey();
    }
  }

  @Override
  public FlowType getFlowType() {
    return FlowType.FLOW_SWITCH;
  }

  public Node getSwitchNode() {
    return switchNode;
  }

  public void setSwitchNode(Node switchNode) {
    this.switchNode = switchNode;
  }
}
